<template>
  <VPage class="app-container">
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <el-input class="w-50" v-model="form.conf_name" placeholder="策略名称"></el-input>
        <el-select
          v-model="form.enable_status"
          placeholder="策略状态"
          class="!w-[160px]"
          clearable
        >
          <el-option
            v-for="item in options['goods.GoodsStatusConfig']?.[0].enableStatusText"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select
          v-model="form.status_type"
          class="!w-[160px]"
          placeholder="状态类型"
          clearable
        >
          <el-option
            v-for="item in options['goods.GoodsStatusConfig']?.[0].statusTypeText"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </template>
      <template #toolbar_btns>
        <VButton
          auth="/goods/basics/product-status-configuration/add"
          type="primary"
          @click="open('add')"
          ><svg-icon icon-class="add_new" />新增</VButton
        >
      </template>
    </VTable>
  </VPage>
  <ComModal ref="addref" @query="query" :options="options"></ComModal>
</template>

<script setup lang="jsx" name="BasicsProduct-status-configuration">
import { ElMessage, ElMessageBox } from "element-plus";
import ComModal from "./components/ComModal.vue";
import { getOptions } from "@/api/index.js";
import {
  queryGoodsStatusConfigList,
  executeGoodsStatusConfig,
  changeStatusConfig,
} from "./api";
import VLog from "@/components/VLog";
import { toRefs } from "vue";
const tableRef = ref();
const addref = ref(null);

const tableOptins = reactive({
  formConfig: {
    data: {},
  },
  rowConfig: {
    height: 70,
  },
  columns: [
    { field: "conf_name", title: "策略名称", minWidth: 100 },
    {
      field: "last_spu_category_text",
      title: "产品分类",
      minWidth: 220,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {" "}
              <VText value={row.last_spu_category_text.join("、")}></VText>
            </div>
          );
        },
      },
    },
    {
      field: "enable_status",
      title: "状态",
      width: 80,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-switch
                disabled={getAuth(
                  "/goods/basics/product-status-configuration/enable-disable"
                )}
                v-model={row.enable_status}
                active-value={0}
                inactive-value={1}
                row={row}
                before-change={beforeChange}
                onChange={() => changeStatus(row)}
              />
            </div>
          );
        },
      },
    },
    {
      field: "status_type_text",
      title: "状态类型",
      width: 120,
    },
    {
      field: "ignore_sku",
      title: "排除SKU",
      minWidth: 120,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <vText value={row.ignore_sku ? row.ignore_sku.join(";") : ""}></vText>
            </div>
          );
        },
      },
    },
    {
      field: "created_user_text",
      title: "排除状态",
      width: 160,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>
                <vText
                  title="开发状态"
                  value={
                    row.ignore_dev_status_text ? row.ignore_dev_status_text.join(";") : ""
                  }
                ></vText>
              </div>
              <div>
                <vText
                  title="销售状态"
                  value={
                    row.ignore_sale_status_text
                      ? row.ignore_sale_status_text.join(";")
                      : ""
                  }
                ></vText>
              </div>
            </div>
          );
        },
      },
    },
    { field: "exec_frequency_text", title: "执行频率", width: 160 },

    {
      field: "remark",
      title: "备注",
      showOverflow: "title",
      width: 160,
    },
    { field: "created_user_text", title: "创建人", width: 160 },
    { field: "created_at", title: "创建时间", width: 180 },
    { field: "updated_at", title: "最新执行时间", width: 180 },
    {
      title: "操作",
      fixed: "right",
      width: 140,
      slots: {
        default: ({ row }) => {
          return (
            <div class="flex">
              <VButton
                type="primary"
                link
                auth="/goods/basics/product-status-configuration/edit"
                onClick={() => open("edit", row)}
              >
                编辑
              </VButton>
              {row.enable_status == 0 ? (
                <VButton
                  type="primary"
                  link
                  auth="/goods/basics/product-status-configuration/manual-execution"
                  onClick={() => handleExecute(row.id)}
                >
                  手动执行
                </VButton>
              ) : (
                ""
              )}
            </div>
          );
        },
      },
    },
  ],

  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => queryGoodsStatusConfigList({ ...form, ...page }),
    },
  },
});
// 列表数据

const query = () => {
  tableRef?.value.query();
};

const data = reactive({
  options: {},
});
const { options } = toRefs(data);

const fetchOption = async () => {
  getOptions({
    version: "v1",
    name: ["goods.GoodsStatusConfig", "goods.GoodsSku"],
  }).then((res) => {
    options.value = res.data;
  });
};
fetchOption();

const open = (type, row) => {
  nextTick(() => {
    addref.value.open(type, row);
  });
};
//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords();
};

const isHandle = () => {
  const records = getSelectRow();
  return !records.length ? ElMessage.error("请先选择行!") && false : true;
};

const handleDelete = () => {
  const records = getSelectRow().map((i) => i.id);
  if (!isHandle()) return;
  ElMessageBox.confirm("此操作将永久删除该项, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await deleteImagesTag({
      id: records,
    });
    ElMessage.success("删除成功");
    query();
  });
};

const beforeChange = (row) => {
  return new Promise((resolve) => {
    ElMessageBox.confirm("是否确认修改当前标签状态?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      return resolve(true);
    });
  });
};

const changeStatus = async (row) => {
  try {
    const res = await changeStatusConfig({
      id: row.id,
      enable_status: row.enable_status,
    });
    ElMessage.success("操作成功");
  } catch (e) {
    throw Error(e);
  }
};

// 手动执行
const handleExecute = async (id) => {
  ElMessageBox.confirm("是否马上执行该策略？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await executeGoodsStatusConfig({
          id,
        });
        ElMessage.success("操作成功");
      } catch (e) {
        throw Error(e);
      }
    })
    .catch(() => {});
};

const getAuth = (val) => {
  return !(window.BTN_AUTH || []).includes(val);
};
</script>
